package cn.leizp.springboot.server.netmanger.config;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.web.server.WebServerFactoryCustomizer;
import org.springframework.boot.web.servlet.server.ConfigurableServletWebServerFactory;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

import java.util.Optional;

@Component
public class MyServerConfig
        implements WebServerFactoryCustomizer<ConfigurableServletWebServerFactory> {

    @Autowired
    private SystemConfigRepository systemConfigRepository;

    @Autowired
    private Environment environment;

    @Value("${server.port:8080}")
    private int defaultPort;

    @Override
    public void customize(ConfigurableServletWebServerFactory factory) {
        // 尝试从命令行参数读取端口: --server-port=8082; IDEA中为 Program arguments
        String portStr = environment.getProperty("server-port");
        if (portStr != null) {
            try {
                int port = Integer.parseInt(portStr);
                factory.setPort(port);
                return;
            } catch (NumberFormatException e) {
                // 命令行参数中的端口号格式错误，继续后续逻辑
            }
        }

        // 尝试从环境变量读取端口： 主要在IDEA中使用
        String portFromEnv = System.getenv("SERVER_PORT");
        if (portFromEnv != null && !portFromEnv.isEmpty()) {
            try {
                int port = Integer.parseInt(portFromEnv);
                factory.setPort(port);
                return;
            } catch (NumberFormatException e) {
                // 环境变量中的端口号格式错误，继续后续逻辑
            }
        }

        try {
            // 尝试从数据库中读取端口
            Optional<SystemConfigEntity> configOptional = systemConfigRepository
                    .findByConfigKey("server.port");
            if (configOptional.isPresent()) {
                int port = Integer.parseInt(configOptional.get().getConfigValue());
                factory.setPort(port);
            } else {
                // 尝试从配置文件读取端口，没有则使用本类中设置的默认值
                int portFromConfig = environment.getProperty("server.port", Integer.class, defaultPort);
                factory.setPort(portFromConfig);
            }
        } catch (Exception e) {
            factory.setPort(defaultPort);
        }
    }
}